<template>
  <div class="main">
    <div class="search-top" style="margin-bottom: 20px">

      <span  style="margin-left: 20px"> 过滤器 </span><br/><br/>
      <!--      <el-input v-bind:text="listQuery.message | capitaliza" placeholder="过滤器" clearable style="width: 200px;"/>-->
      <div>
        首字母大写的过滤器：<input type="text" v-model="message" placeholder="过滤器"><br/>
        <p>{{ message | capitalize }}</p>
        <br/>
      </div>

      <div>
        <span  style="margin-left: 20px"> 计算属性 </span><br/><br/>
        数量：<input type="text" v-model="price" placeholder="数量">
        单价：<input type="text" v-model="count" placeholder="单价">
        总价：{{prices}}
      </div>
      <br/>
      <br/>


      <div>
        <span  style="margin-left: 20px"> 监听器 </span><br/><br/>
        斤数：<input type="text" v-model="jin" placeholder="斤数">
        千克数：<input type="text" v-model="kg" placeholder="千克数">
      </div>
      <br/>
      <br/>


      <div>
        <span  style="margin-left: 20px"> 组件的使用 </span><br/><br/>
        <div>
          <button-counter></button-counter>
          <button-counter></button-counter>
          <button-counter></button-counter>
        </div>
        <br/>

        <span  style="margin-left: 10px"> prop传递父组件的数值 </span><br/><br/>
        <div>
          父组件的值：<input type="text" v-model="parentMessage">
          <my-component :amessage="parentMessage"/>
        </div>
        <br/>

        <span  style="margin-left: 10px"> 子组件传递给父组件数据 </span><br/>
        <div>
          <p>父组件：{{sum}}</p>
          <my-sum @increase="handleGet"
                  @reduce="handleGet"/>
        </div>
      </div>
      <br/>
      <br/>

      <div>
        <router-link style='margin-left: 10px' to="test3">我是一个路由  </router-link>
        <router-link style='margin-left: 10px' to="test4">我是用来实验的一个路由</router-link>
      </div>
      <br/>

      <span style="margin-left: 10px">关键字：</span>
      <el-input v-model="listQuery.kw" placeholder="姓名 地址" clearable style="width: 200px;"
                @keyup.enter.native="search"/>
      <span style="margin-left: 10px">状态：</span>
      <el-select v-model="listQuery.sb" clearable style="width: 150px;" @change="selectedChange" placeholder="请选择">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
        <el-button type="success" style="margin-left: 10px" icon="el-icon-search" @click="search">查询</el-button>
        <el-button type="primary" style="margin-left: 10px" icon="el-icon-plus" @click="add">添加</el-button>
        <el-button type="warning" style="margin-left: 10px" :disabled="multipleSelection.length !== 1"
                   icon="el-icon-edit" @click="toEdit(multipleSelection)">修改
        </el-button>
        <el-button type="danger" style="margin-left: 10px" :disabled="multipleSelection.length === 0"
                   icon="el-icon-delete" @click="toDel(multipleSelection)">删除
        </el-button>

      <el-table
        ref="multipleTable"
        tooltip-effect="dark"
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180">
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          sortable
          width="180">
          <template slot-scope="{row}">
            <el-tag :type="row.status | statusFilter">
              {{ row.status | contentFilter }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="address"
          label="地址">
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建日期"
          width="230">
        </el-table-column>
        <el-table-column
          prop="updateTime"
          label="更新日期"
          width="230">
        </el-table-column>
        <el-table-column
          label="操作"
          width="150">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.pi"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="listQuery.ps"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background>
        </el-pagination>
      </div>
      <newDialog ref="newDialog" @save="fetchUserList"/>
      <!--<div>
        <router-link to="test1">自定义指令</router-link>
        <router-link to="test2">监听属性</router-link>
        <router-link to="main1">主页</router-link>
      </div>-->
    </div>
  </div>
</template>

<script>
import newDialog from './newDialog'
import axios from 'axios'

// Vue.component('button-counter', {
//   data: function () {
//     return {
//       count: 0
//     }
//   },
//   template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
// })

export default {
  name: 'Main',
  // 组件的引用
  components: {
    newDialog ,    // 引用另一个页面
    "button-counter":{
      // 使用组件所需要返回的值
      data: function (){
        return {
          num: 0        // 返回值要和数据绑定的变量名相同
        }
      },
      // 这里{{}}里的num要和返回值绑定的实参相同才能进行数值之间的绑定
      // 如果是使用的外部引用变量的话，那么多个应用就会是相同的值了。比如说上面return的不是num而是count这个外部变量(假设已经定义好了)，那么组件所触发的值都是公用的。
      template: '<button v-on:click="num++">You clicked me {{ num }} times.</button>'       // 这里的num并不是vue对象中所需要互相绑定的数据，而是在定义组件中所绑定的数据。
    },
    // 父组件通信
    "my-component":{
      props: ["amessage"],
      template: "<div>子组件接收到的值：{{amessage}}</div>"
    },
    // 子组件想父组件通信
    "my-sum": {
      data: function(){
        return {
          counter: 0
        }
      },
      methods:{
        handleIncrease: function(){
          this.counter++;
          this.$emit("increase", this.counter);
        },
        handleReduce: function(){
          this.counter--;
          this.$emit("reduce", this.counter);
        }
      },
      template: "<div>子组件：<button @click='handleIncrease'>+1</button><button @click='handleReduce'>-1</button></div>"
    }
  },
  // 过滤器
  filters: {
    // 首字母变为大写
    capitalize: function (value) {
      if (!value) return ''
      value = value.toString()
      return value.charAt(0).toUpperCase() + value.slice(1)
    },
    statusFilter(status) {
      const statusMap = {
        0: 'danger',
        1: 'success',
        2: 'primary',
        3: 'warning',
        4: 'info'
      };
      return statusMap[status]
    },
    contentFilter(type){
      const styleMap = {
        0: '禁用',
        1: '正常',
        2: '待审核',
        3: '异常',
        4: '未知'
      };
      return styleMap[type]
    }
  },
  data () {
    return {
      listQuery:{
        pi: 1,
        ps: 10,
        kw: '',
        sb: ''
      },
      options: [{
        value: '0',
        label: '禁用'
      }, {
        value: '1',
        label: '正常'
      }, {
        value: '2',
        label: '待审核'
      }, {
        value: '3',
        label: '异常'
      }, {
        value: '4',
        label: '未知'
      }],
      multipleSelection: [],
      idList: [],
      tableData: [],
      message: '',  //过滤器中的消息
      price: '',    //单价       计算属性
      count: "",    //数量
      jin: "",      //斤数       监听器
      kg: "",       //千克数
      // num: 0,       //次数       组件     这个不是组件定义中所绑定的数据，这是个误区
      parentMessage: "",//父组件的变量
      sum: 0,       // 子组件与父组件通信的变量
      total: 0
    }
  },
  // 计算属性
  computed: {
    prices: function () {
      var prices = 0;
      prices += this.price * this.count;
      return prices;
    }
  },
  // 监听器
  watch: {
    jin: function (val) {
      this.jin = val;
      this.kg = val / 2.0;
    },
    kg: function (val) {
      this.jg = val;
      this.jin = val * 2;
    },
    'listQuery.kw' (curVal, oldVal) {
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        this.handleChangeName(curVal, oldVal)
      }, 2000)
    }
  },
  created(){
    this.fetchUserList()
  },
  methods: {
    handleGet: function(sum){
      this.sum = sum;
    },
    fetchUserList(){
      axios.get("http://192.168.70.91:8088/my-server/user/finduserlist",{params:this.listQuery}).then(res => {
        this.tableData = res.data.data.list
        this.total = res.data.data.totalRow
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleChangeName (curVal, oldVal) { //对应2
      if (curVal === '' && oldVal === '') {
        return false;
      }
      this.listQuery.kw = curVal;
      console.log(this.listQuery)
      //此处可调用后台查询接口
      this.fetchUserList()
    },
    search(){
      //搜索按钮
      this.listQuery.pi = 1
      this.fetchUserList()
    },
    add(){
      this.$ref.newDialog.dialog = true
      this.$refs.newDialog.title = '新增'
      this.$refs.newDialog.isAdd = true
      this.$refs.newDialog.form = {}
    },
    selectedChange(value){
      this.listQuery.sb = value
      this.fetchUserList()
    },
    //打开编辑弹窗
    handleEdit(index,row){
      axios.get("http://192.168.70.91:8088/my-server/user/finduserbyid",{params:{id:row.id}}).then(res => {
        this.$refs.newDialog.form = res.data.data
      })
      this.$refs.newDialog.dialog = true
      this.$refs.newDialog.title = '编辑'
      this.$refs.newDialog.isAdd = false
    },
    toEdit(checkData){
      axios.get("http://192.168.70.91:8088/my-server/user/finduserbyid",{params:{id:checkData[0].id}}).then(res => {
        this.$refs.newDialog.form = res.data.data
      })
      this.$refs.newDialog.dialog = true
      this.$refs.newDialog.title = '编辑'
      this.$refs.newDialog.isAdd = false
    },
    // 删除
    handleDelete(index, row) {
      this.$confirm(`是否删除"${row.username}"`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        axios.post("http://192.168.70.91:8088/my-server/user/deleteuser",{id:row.id}).then(res => {
          if (res.data.succ) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.fetchUserList()
          } else {
            this.$message({
              message: '删除失败',
              type: 'warning'
            })
          }
        }).catch(error => {
          console.log(error)
        })
      }).catch(() => {
      })
    },
    //上面删除
    toDel(data){
      this.idList = []
      data.forEach(item => {
        this.idList.push(item.id)
      })
      this.$confirm('此操作将永久删除选中的文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        const data = {
          ids: this.idList
        };
        axios.post("http://192.168.70.91:8088/my-server/user/deletebyids",data).then(res => {
          if (res.data.succ) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.fetchUserList();
          } else {
            this.$message({
              message: '删除失败',
              type: 'warning'
            })
          }
        }).catch(error => {
          console.log(error)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 切换分页大小
    handleSizeChange(val) {
      this.listQuery.ps = val
      this.fetchUserList()
    },
    // 分页
    handleCurrentChange(val) {
      this.listQuery.pi = val
      this.fetchUserList()
    }
  }
}
</script>

<style scoped>

</style>
